import { MongoClient } from "mongodb";
import bcrypt from "bcryptjs";
import dotenv from "dotenv";

dotenv.config();

const MONGODB_URI =
  process.env.MONGODB_URI || "mongodb://localhost:27017/login-system";

async function initDatabase() {
  let client;

  try {
    console.log("🔄 正在初始化数据库...");

    client = new MongoClient(MONGODB_URI);
    await client.connect();

    const db = client.db();
    const users = db.collection("users");
    const customers = db.collection("customers");

    // 检查管理员是否存在
    const adminExists = await users.findOne({ username: "admin" });

    if (!adminExists) {
      // 创建管理员账号
      const adminPassword = await bcrypt.hash("123456", 10);
      await users.insertOne({
        username: "admin",
        email: "admin@example.com",
        password: adminPassword,
        role: "admin",
        createdAt: new Date(),
        updatedAt: new Date(),
        loginCount: 0,
      });
      console.log("✅ 管理员账号创建成功: admin / 123456");
    }

    // 检查普通用户是否存在
    const userExists = await users.findOne({ username: "user001" });

    if (!userExists) {
      // 创建普通用户账号
      const userPassword = await bcrypt.hash("123456", 10);
      await users.insertOne({
        username: "user001",
        email: "user001@example.com",
        password: userPassword,
        role: "user",
        createdAt: new Date(),
        updatedAt: new Date(),
        loginCount: 0,
      });
      console.log("✅ 普通用户账号创建成功: user001 / 123456");
    }

    // 创建更多测试用户
    const testUsers = [
      { username: "test001", email: "test001@example.com", role: "user" },
      { username: "test002", email: "test002@example.com", role: "user" },
      { username: "manager", email: "manager@example.com", role: "admin" },
    ];

    for (const testUser of testUsers) {
      const exists = await users.findOne({ username: testUser.username });
      if (!exists) {
        const password = await bcrypt.hash("123456", 10);
        await users.insertOne({
          ...testUser,
          password,
          createdAt: new Date(),
          updatedAt: new Date(),
          loginCount: 0,
        });
        console.log(`✅ 测试用户创建成功: ${testUser.username} / 123456`);
      }
    }

    // 创建客户集合索引
    await customers.createIndex({ phone: 1 }, { unique: true });
    await customers.createIndex({ name: 1 });
    await customers.createIndex({ status: 1 });
    await customers.createIndex({ createdAt: -1 });
    console.log("✅ 客户集合索引创建成功");

    // 创建示例客户数据
    const sampleCustomers = [
      {
        name: "张三",
        phone: "13800138001",
        wechat: "zhangsan001",
        idCardFront: "",
        idCardBack: "",
        alipay: "zhangsan@alipay.com",
        bankCard: "6222021234567890123",
        bankName: "中国工商银行",
        status: "active",
        createdAt: new Date(),
        updatedAt: new Date(),
      },
      {
        name: "李四",
        phone: "13800138002",
        wechat: "lisi002",
        idCardFront: "",
        idCardBack: "",
        alipay: "lisi@alipay.com",
        bankCard: "6222021234567890124",
        bankName: "中国建设银行",
        status: "active",
        createdAt: new Date(),
        updatedAt: new Date(),
      },
      {
        name: "王五",
        phone: "13800138003",
        wechat: "wangwu003",
        idCardFront: "",
        idCardBack: "",
        alipay: "wangwu@alipay.com",
        bankCard: "6222021234567890125",
        bankName: "中国农业银行",
        status: "inactive",
        createdAt: new Date(),
        updatedAt: new Date(),
      },
    ];

    for (const customer of sampleCustomers) {
      const exists = await customers.findOne({ phone: customer.phone });
      if (!exists) {
        await customers.insertOne(customer);
        console.log(`✅ 示例客户创建成功: ${customer.name}`);
      }
    }

    console.log("🎉 数据库初始化完成！");
  } catch (error) {
    console.error("❌ 数据库初始化失败:", error);
  } finally {
    if (client) {
      await client.close();
    }
  }
}

initDatabase();
